<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-4xl mx-auto">
      <h2 class="text-2xl font-bold mb-6">确认订单</h2>

      <!-- 收货地址 -->
      <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b">
          <h3 class="text-lg font-medium">收货地址</h3>
        </div>
        <div class="p-4">
          <div class="flex items-start gap-4">
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-1">
                <span class="font-bold">{{ address?.name }}</span>
                <span class="text-gray-600">{{ address?.phone }}</span>
              </div>
              <p class="text-gray-600">{{ address?.address }}</p>
            </div>
            <el-button type="primary" link @click="handleChangeAddress">更换地址</el-button>
          </div>
        </div>
      </div>

      <!-- 商品列表 -->
      <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 border-b">
          <h3 class="text-lg font-medium">商品信息</h3>
        </div>
        <div class="divide-y">
          <div
            v-for="item in orderItems"
            :key="item.id"
            class="p-4 flex items-center gap-4"
          >
            <img
              :src="item.product.image"
              :alt="item.product.name"
              class="w-20 h-20 object-cover rounded"
            >
            <div class="flex-1">
              <h4 class="font-medium">{{ item.product.name }}</h4>
              <p class="text-gray-500 text-sm mt-1">{{ item.product.description }}</p>
            </div>
            <div class="text-right">
              <p class="text-gray-600">x{{ item.quantity }}</p>
              <p class="text-primary font-bold mt-1">¥{{ item.product.price * item.quantity }}</p>
            </div>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="bg-white rounded-lg shadow mb-6">
        <div class="p-4 space-y-3">
          <div class="flex justify-between">
            <span class="text-gray-600">商品总价</span>
            <span>¥{{ totalAmount }}</span>
          </div>
          <div class="flex justify-between">
            <span class="text-gray-600">运费</span>
            <span>¥{{ shipping }}</span>
          </div>
          <div class="flex justify-between text-lg font-bold">
            <span>实付金额</span>
            <span class="text-primary">¥{{ totalAmount + shipping }}</span>
          </div>
        </div>
      </div>

      <!-- 底部提交按钮 -->
      <div class="flex justify-end">
        <el-button type="primary" size="large" @click="handleSubmit">
          提交订单
        </el-button>
      </div>
    </div>

    <!-- 选择地址对话框 -->
    <el-dialog
      v-model="showAddressDialog"
      title="选择收货地址"
      width="90%"
      style="max-width: 600px"
      top="15vh"
    >
      <div class="space-y-4">
        <el-empty v-if="!addresses.length" description="暂无收货地址">
          <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
        </el-empty>

        <template v-else>
          <div class="mb-4 text-right">
            <el-button type="primary" @click="handleAddAddress">新增地址</el-button>
          </div>

          <el-radio-group v-model="selectedAddressId" class="w-full">
            <el-card
              v-for="address in addresses"
              :key="address.id"
              class="mb-4 cursor-pointer hover:shadow-md transition-shadow"
              :class="{ 'border-primary': selectedAddressId === address.id }"
              @click="selectedAddressId = address.id"
            >
              <div class="flex items-center">
                <el-radio :value="address.id" class="flex-1">
                  <div class="ml-2">
                    <div class="flex items-center gap-2 mb-1">
                      <span class="font-bold">{{ address.name }}</span>
                      <span class="text-gray-600">{{ address.phone }}</span>
                      <el-tag v-if="address.isDefault" type="success" size="small">默认地址</el-tag>
                    </div>
                    <p class="text-gray-600">{{ address.address }}</p>
                  </div>
                </el-radio>
              </div>
            </el-card>
          </el-radio-group>
        </template>
      </div>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="showAddressDialog = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!selectedAddressId && addresses.length > 0"
            @click="handleConfirmAddress"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useCartStore } from '@/stores/cart'
import { getCheckoutInfo, createOrder } from '@/api/checkout'
import { getAddresses } from '@/api/address'
import {ElMessage} from "element-plus";

const route = useRoute()
const router = useRouter()

const showAddressDialog = ref(false)
const selectedAddressId = ref(undefined)
const shipping = ref(0) // 运费
const loading = ref(false)
const addresses = ref([])
const checkoutInfo = ref({
  items: [],
  address: null,
  totalAmount: 0,
})

// 获取地址列表
const fetchAddresses = async () => {
  try {
    const {data} = await getAddresses()
    addresses.value = data.map(item => {
      return {
        ...item,
        isDefault: Boolean(item.isDefault),
        address:`${item.region.join('')}${item.detail}`
      }
    })
    // 选中传来的地址
    const defaultAddress = addresses.value.find(addr => addr.id = route.query.addressId)
    if (defaultAddress) {
      selectedAddressId.value = defaultAddress.id
    }
  } catch (error) {
    ElMessage.error('获取地址列表失败')
  }
}

// 获取结算信息
const fetchCheckoutInfo = async () => {
  try {
    loading.value = true
    const cartItemIds = route.query.items?.split(',').map(Number) || []
    checkoutInfo.value = await getCheckoutInfo(cartItemIds)
  } catch (error) {
    ElMessage.error('获取结算信息失败')
  } finally {
    loading.value = false
  }
}

// 当前选中的地址
const address = computed(() =>
  addresses.value.find(addr => addr.id === selectedAddressId.value)
)

// 订单商品列表
const orderItems = computed(() => checkoutInfo.value.items)

// 订单总金额
const totalAmount = computed(() => {
  return checkoutInfo.value.items.reduce((total, item) => total + item.product.price * item.quantity, 0)
})

// 更换地址
const handleChangeAddress = () => {
  showAddressDialog.value = true
}

// 新增地址
const handleAddAddress = () => {
  router.push('/address')
}

// 确认选择地址
const handleConfirmAddress = () => {
  showAddressDialog.value = false
}

// 提交订单
const handleSubmit = async () => {
  if (!address.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  try {
    loading.value = true
    await createOrder({
      items: orderItems.value,
      addressId: address.value.id
    })

    ElMessage.success('下单成功')
    await router.push(`/orders?status=pending`)
  } catch (error) {
    ElMessage.error('下单失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchAddresses()
  fetchCheckoutInfo()
})
</script>

<style scoped>
/* 选中的地址卡片样式 */
.border-primary {
  border: 2px solid var(--el-color-primary);
}

/* 移动端优化 */
@media (max-width: 640px) {
  :deep(.el-dialog) {
    width: 90% !important;
    margin: 50px auto !important;
  }
}
</style>
